package com.hdss996.dictationread.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.hdss996.dictationread.ocr.JsonParser;
import com.hdss996.dictationread.R;
import com.hdss996.dictationread.ocr.RecognizeService;
import com.hdss996.dictationread.util.AudioUtil;
import com.hdss996.dictationread.util.FileUtil;
import com.hdss996.dictationread.util.StatusBarUtil;
import com.hdss996.dictationread.util.SysToolUtil;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class DictationModeActivity extends AppCompatActivity {
    private Map<String, String> tts_map = new HashMap<String, String>();
    private SysToolUtil sysToolUtil = new SysToolUtil();
    private Context mc = DictationModeActivity.this;
    private EditText aet;
    private TextToSpeech tts;
    private EditText et;
    private TextView tb;
    private TextView tb_hide;
    private ImageView backBtn;
    private ImageView speakBtn;
    private ImageView stopBtn;
    private ImageView trimBtn;
    private ImageView saveBtn;
    private ImageView openConfigBtn;

    private ImageButton cameraButton;
    private ImageButton lastButton;
    private ImageButton pauseButton;
    private ImageButton playButton;
    private ImageButton nextButton;

    private LinearLayout camera_L;
    private LinearLayout openConfigLinear;
    private LinearLayout config_panl;
    private LinearLayout playControl;

    private TextView textNum;
    private Spinner ttsListSp;
    private SeekBar pitchBar;//音调bar
    private SeekBar speechRateBar;//语速bar
    private Switch loop_switch;
    private float pitchNum = 1.0f;
    private float speechRateNum = 1.0f;
    private int config_panl_state = 0;
    private boolean isLoop = true;
    private EditText loop_num_et;
    private int loopNum = 3;
    private String dic_start_str;
    private String dic_end_str;
    private int terms;//用于记录词语总数
    private Handler handler;
    private HashMap<String,String> params;
    private String currentWordIndex;// 用于记录当前正在朗读的单词索引

    private static final int REQUEST_CODE_GENERAL_BASIC = 106;//百度OCR通用文字识别

    private boolean hasGotToken = false;
    private AlertDialog.Builder alertDialog;

    private static final String TAG = "MyTtsManager";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dictationmode);
        StatusBarUtil.transparencyBar(this); //设置状态栏全透明
        StatusBarUtil.StatusBarLightMode(this); //设置白底黑字

        //初始化控件
        initView();
        //初始化数据
        initData();
        // 拍照识别初始化方式
        initAccessToken();
        //初始化按钮
        initListener();
    }

    //控件初始化方法
    private void initView() {
        //初始化控件
        tb = findViewById(R.id.top_bar);
        tb_hide = findViewById(R.id.hide);
        backBtn = findViewById(R.id.backBtn);
        et = findViewById(R.id.textarea);
        cameraButton = findViewById(R.id.cameraButton);
        camera_L = findViewById(R.id.camera_L);
        speakBtn = findViewById(R.id.speakBtn);
        stopBtn = findViewById(R.id.stopBtn);

        playControl = findViewById(R.id.playControl);
        lastButton = findViewById(R.id.lastButton);
        pauseButton = findViewById(R.id.pauseButton);
        playButton = findViewById(R.id.playButton);
        nextButton = findViewById(R.id.nextButton);

        trimBtn = findViewById(R.id.trimBtn);
        saveBtn = findViewById(R.id.saveBtn);
        openConfigBtn = findViewById(R.id.openConfigBtn);
        openConfigLinear = findViewById(R.id.openConfigLinear);
        config_panl = findViewById(R.id.config_panl);
        textNum = findViewById(R.id.tv_text_num);
        pitchBar = findViewById(R.id.pitchBar);
        speechRateBar = findViewById(R.id.speechRateBar);
        ttsListSp = findViewById(R.id.ttsListSp);
        loop_switch = findViewById(R.id.loop_switch);
        loop_num_et = findViewById(R.id.loop_num_et);
    }
    // 数据初始化方法
    private void initData() {
        // 初始化Handler
        handler = new Handler();
        // 初始化参数Map
        params = new HashMap<String, String>();
        // 初始化警告对话框
        alertDialog = new AlertDialog.Builder(this);

        // 获取语音引擎列表
        getTtsListData();

        // 在UI线程中更新控件状态
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // 设置“播放”按钮可见
                speakBtn.setVisibility(View.VISIBLE);
                // 设置“打开配置”按钮可见
                openConfigBtn.setVisibility(View.VISIBLE);
                // 设置“打开配置”按钮的背景样式
                openConfigLinear.setBackgroundResource(R.drawable.def_mode_btn_white);
                // 设置相机按钮可见
                cameraButton.setVisibility(View.VISIBLE);
                // 设置相机按钮的背景样式
                camera_L.setBackgroundResource(R.drawable.def_mode_btn_white);
                // 隐藏播放控控制面板
                playControl.setVisibility(View.GONE);
                // 隐藏停止播放按钮
                stopBtn.setVisibility(View.GONE);
                // 隐藏遮挡层控件
                tb_hide.setVisibility(View.GONE);
                // 加载并显示历史数据
                historyText("read");
            }
        });
    }
    //按钮初始化方法
    private void initListener() {
        //返回主页面
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });
        //清空文本
        trimBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                et.setText("");
                if (tts.isSpeaking()) {
                    tts.stop();
                    setTextViewWord(tb, "听写模式");
                    //开启滑块
                    onOffSeekBar(true);
                }
            }
        });
        //保存音频
        // 点击保存按钮的监听器
        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // 处理保存按钮点击事件
                //handleSaveButtonClick();
                //功能完善中。。。
                showAlert("提示","功能完善中。。。","知道了");
            }
        });

        //输入框监听时间
        et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                historyText("write");
            }
        });
        // 设置相机按钮的点击事件监听器
        cameraButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 检查百度AI的访问令牌是否有效
                if (!checkTokenStatus()) {
                    return; // 如果访问令牌无效，直接返回，不执行后续操作
                }
                // 创建一个意图，启动相机活动
                Intent intent = new Intent(DictationModeActivity.this, CameraActivity.class);
                // 将输出文件路径作为额外数据放入意图中
                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                        FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath());
                // 将内容类型设置为通用文字识别
                intent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                        CameraActivity.CONTENT_TYPE_GENERAL);
                // 启动相机活动，并等待返回结果
                startActivityForResult(intent, REQUEST_CODE_GENERAL_BASIC);
            }
        });

        //打开参数配置面板
        openConfigBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (config_panl_state == 0) {
                    //参数面板
                    config_panl.setVisibility(View.VISIBLE);
                    config_panl.setAnimation(AnimationUtils.makeInAnimation(DictationModeActivity.this, true));
                    config_panl_state = 1;
                } else {
                    //参数面板
                    config_panl.setVisibility(View.GONE);
                    config_panl.setAnimation(AnimationUtils.makeOutAnimation(DictationModeActivity.this, false));
                    config_panl_state = 0;
                }

            }
        });
        // 设置ttsListSp下拉列表的选项选择监听器
        ttsListSp.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // 当选择了下拉列表中的某一项时触发
                // 从tts_map中获取所选项对应的TTS引擎包名，并设置为当前TTS引擎
                tts.setEngineByPackageName(Objects.requireNonNull(tts_map.get(ttsListSp.getSelectedItem().toString())));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 当没有任何选项被选中时触发
                // 在此处不执行任何操作
            }
        });
        //音调监听事件
        pitchBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            //滑动滑块时触发
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            //滑动开始时触发
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            //滑动停止时触发
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (seekBar.getId() == R.id.pitchBar) {
                    pitchNum = pitchBar.getProgress() * 0.1f;
                    tts.setSpeechRate(pitchNum);
                }
            }
        });
        //语速监听事件
        speechRateBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            //滑动滑块时触发
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            //滑动开始时触发
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            //滑动停止时触发
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (seekBar.getId() == R.id.speechReadRateBar) {
                    speechRateNum = speechRateBar.getProgress() * 0.1f;
                    tts.setSpeechRate(speechRateNum);
                }
            }
        });
        //循环按钮
        loop_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isLoop = isChecked;
                loop_num_et.setFocusable(isChecked);
                loop_num_et.setClickable(isChecked);
                loop_num_et.setFocusableInTouchMode(isChecked);
            }
        });


        //开始朗读
        speakBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                tts.setPitch(pitchNum);
                tts.setSpeechRate(speechRateNum);
                //设置循环次数
                setLoopNum();

                String str = et.getText().toString().trim();
                if (str.isEmpty()) {
                    showEmptyContentAlert();
                } else {
                    speakWords(str);
                }
            }
        });
        //停止朗读
        stopBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (tts != null) {
                    tts.stop();
                    playSeekBar(false);
                    onOffSeekBar(true);
                    setTextViewWord(tb, "听写模式");
                    setTextViewWord(textNum, terms + "个词");
                }
            }
        });
        //上一个按钮
        lastButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                lastTTS(currentWordIndex);
            }
        });
        //暂停按钮
        pauseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pauseTTS(currentWordIndex);
            }
        });
        //续播按钮
        playButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                playTTS(currentWordIndex);
            }
        });
        //下一个按钮
        nextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                nextTTS(currentWordIndex);
            }
        });
    }


    /**
     * 以license文件方式初始化百度OCR访问令牌
     */
    private void initAccessToken() {
        OCR.getInstance(getApplicationContext()).initAccessToken(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken accessToken) {
                // 获取访问令牌并标记为已获取
                String token = accessToken.getAccessToken();
                hasGotToken = true;
            }

            @Override
            public void onError(OCRError error) {
                // 打印错误信息
                error.printStackTrace();
                // 显示提示对话框，提醒用户联网不成功，无法使用拍照识图
                showAlert("提示", "联网不成功，无法使用拍照识字！\n请检查网络连接！\n其他功能可正常使用！", "好的");
            }
        }, getApplicationContext());
    }
    /**
     * 检查百度OCR访问令牌的状态
     * @return 访问令牌是否有效
     */
    private boolean checkTokenStatus() {
        if (!hasGotToken) {
            // 如果访问令牌无效，显示提示信息
            Toast.makeText(getApplicationContext(), "联网不成功，无法使用！", Toast.LENGTH_LONG).show();
        }
        return hasGotToken;
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // 用户授权成功，初始化百度OCR访问令牌
            initAccessToken();
        } else {
            // 用户拒绝授权，显示提示信息
            Toast.makeText(getApplicationContext(), "授权失败，无法使用拍照识字功能！", Toast.LENGTH_LONG).show();
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data); // 调用父类的onActivityResult方法，确保父类中的逻辑得到执行

        // 识别成功回调，通用文字识别
        if (requestCode == REQUEST_CODE_GENERAL_BASIC && resultCode == Activity.RESULT_OK) { // 检查返回的请求码和结果码，确保是通用文字识别的返回结果

            // 对拍摄的图片进行通用文字识别
            RecognizeService.recGeneralBasic(getApplicationContext(), FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath(),
                    new RecognizeService.ServiceListener() { // 调用通用文字识别服务的方法，传入图片文件路径和回调监听器

                        @Override
                        public void onResult(String result) { // 实现回调监听器的onResult方法，处理通用文字识别的结果

                            // 将识别结果拼接到文本编辑框中
                            String str = et.getText().toString(); // 获取文本编辑框中的文本内容
                            //分词后拼接
                            StringBuilder sb = getStringBuilder(result, str);

                            et.setText(sb); // 将拼接好的识别结果和文本编辑框中的内容显示在文本编辑框中
                        }
                    });
        }
    }


    //分词拼接方法
    @NonNull
    private static StringBuilder getStringBuilder(String result, String str) {

        String[] resultWords = JsonParser.extractWords(result); // 从通用文字识别的结果中提取识别出的单词
        String joinedWords = TextUtils.join(" ", resultWords); // 使用TextUtils.join方法将识别出的单词连接成一个字符串，用空格分隔


        StringBuilder sb = new StringBuilder(); // 创建一个StringBuilder对象，用于拼接识别结果和文本编辑框中的内容
        if (!str.isEmpty()) { // 如果文本编辑框不为空
            sb.append(str).append("\n"); // 将其内容拼接到StringBuilder中
        }
        sb.append(joinedWords);

        // 使用正则表达式将词语按空格或标点符号分割
        participleSplicing splicingResult = getParticipleSplicing(sb.toString());
        return new StringBuilder(splicingResult.appendedWords);
    }

    // 该方法用于将给定的字符串转换为单词数组，并逐个单词进行语音合成
    private void speakWords(String str) {
        //分词后拼接
        participleSplicing splicingResults = getParticipleSplicing(str);
        // 将连接后的字符串设置为文本框的内容
        et.setText(splicingResults.appendedWords);

        // 设置界面显示为“听写模式 播报中。。。”
        setTextViewWord(tb, "听写模式  播报中。。。");

        // 关闭SeekBar的交互功能
        onOffSeekBar(false);

        // 隐藏配置面板
        config_panl.setVisibility(View.GONE);

        playSeekBar(false);

        params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"0");
        // 使用TTS对象朗读“开始听写”的提示语句，并在队列中添加
        tts.speak(dic_start_str, TextToSpeech.QUEUE_ADD, params);
        // 在TTS队列中添加一个静默的语音合成，持续2000毫秒，用于增加语音之间的间隔
        tts.playSilentUtterance(2000, TextToSpeech.QUEUE_ADD,"0" );

        // 调用speakWordsFromIndex方法，从第一个单词开始播报
        speakWordsFromIndex(splicingResults.words,"0");
    }
    //按循环播报的方法
    private void speakWordWithLoop(String word, int loopNum) {
        for (int i = 0; i < loopNum; i++) {
            tts.speak(word, TextToSpeech.QUEUE_ADD, params);
            tts.playSilentUtterance(3000, TextToSpeech.QUEUE_ADD, params.get(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID));
        }
    }
    // 用于从指定索引开始朗读的方法
    private void speakWordsFromIndex(String[] words, String startIndex) {
        for (int i = Integer.parseInt(startIndex); i < terms; i++) {
            params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,Integer.toString(i+1));
            String word = words[i];
            // 调用speakWordWithLoop方法对单词进行语音合成，并根据需要重复播放
            speakWordWithLoop(word, loopNum);
        }

        params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"-1");
        // 使用TTS对象朗读“听写结束”的提示语句，并在队列中添加
        //tts.speak(dic_end_str, TextToSpeech.QUEUE_ADD, null, getString(R.string.app_name));
        tts.speak(dic_end_str,TextToSpeech.QUEUE_ADD,params);
    }

    @NonNull
    private static participleSplicing getParticipleSplicing(String str) {
        // 使用正则表达式将字符串分割为单词数组
        String[] words = str.split("[\\p{P}\\p{S}\\s]+");
        // 使用TextUtils.join()方法将数组中的元素连接起来
        String joinedWords = TextUtils.join(",    ", words);
        return new participleSplicing(words, joinedWords);
    }
    private static class participleSplicing {
        public final String[] words;
        public final String appendedWords;

        public participleSplicing(String[] words, String joinedWords) {
            this.words = words;
            this.appendedWords = joinedWords;
        }
    }


    // 在暂停按钮的点击事件中调用该方法
    public void pauseTTS(String utteranceId) {
        if (tts != null && utteranceId != null) {
            if (Integer.parseInt(utteranceId) == 0) {
                Toast.makeText(mc, "即将开始，请准备！", Toast.LENGTH_SHORT).show();
            }else if(Integer.parseInt(utteranceId) == -1){
                Toast.makeText(mc, "听写结束！", Toast.LENGTH_SHORT).show();
            }else {
                playSeekBar(true);
                Toast.makeText(mc, "暂停！", Toast.LENGTH_SHORT).show();
                tts.stop();  // 停止当前的朗读
            }
        }
    }
    // 在继续按钮的点击事件中调用该方法
    public void playTTS(String utteranceId) {
        String str = et.getText().toString().trim();
        // 使用正则表达式将字符串分割为单词数组
        String[] words = str.split("[\\p{P}\\p{S}\\s]+");
        if (utteranceId!=null){
            if (Integer.parseInt(utteranceId) == 0){
                Toast.makeText(mc, "即将开始，请等待！", Toast.LENGTH_SHORT).show();
            }else if (Integer.parseInt(utteranceId) == -1) {
                Toast.makeText(mc, "听写已结束，请检查！", Toast.LENGTH_SHORT).show();
            } else if (Integer.parseInt(utteranceId) > 0) {
                if (tts != null) {
                    Toast.makeText(mc, "继续播放！", Toast.LENGTH_SHORT).show();
                    playSeekBar(false);
                    tts.stop();
                    speakWordsFromIndex(words, String.valueOf(Integer.parseInt(currentWordIndex) - 1));  // 从上一个单词继续朗读
                }
            }
        }
    }
    // 在上一个按钮的点击事件中调用该方法
    public void lastTTS(String utteranceId) {
        String str = et.getText().toString().trim();
        // 使用正则表达式将字符串分割为单词数组
        String[] words = str.split("[\\p{P}\\p{S}\\s]+");
        if (utteranceId!=null){
            if (Integer.parseInt(utteranceId) == 0){
                Toast.makeText(mc, "即将开始，请等待！", Toast.LENGTH_SHORT).show();
            }else if (Integer.parseInt(utteranceId) == 1 ) {
                Toast.makeText(mc, "这是第一个词语！", Toast.LENGTH_SHORT).show();
            } else if (Integer.parseInt(utteranceId) == -1) {
                Toast.makeText(mc, "听写已结束，请检查！", Toast.LENGTH_SHORT).show();
            } else if (Integer.parseInt(utteranceId) > 1) {
                if (tts != null) {
                    playSeekBar(false);
                    Toast.makeText(mc, "上一个！", Toast.LENGTH_SHORT).show();
                    tts.stop();
                    speakWordsFromIndex(words, String.valueOf(Integer.parseInt(currentWordIndex) - 2));  // 从上一个单词继续朗读
                }
            }
        }
    }
    // 在下一个按钮的点击事件中调用该方法
    public void nextTTS(String utteranceId) {
        String str = et.getText().toString().trim();
        // 使用正则表达式将字符串分割为单词数组
        String[] words = str.split("[\\p{P}\\p{S}\\s]+");
        if (utteranceId!=null){
            if (Integer.parseInt(utteranceId) == 0){
                Toast.makeText(mc, "即将开始，请等待！", Toast.LENGTH_SHORT).show();
            }else if (Integer.parseInt(utteranceId) ==  words.length) {
                Toast.makeText(mc, "这是最后一个词语！", Toast.LENGTH_SHORT).show();
            } else if (Integer.parseInt(utteranceId) == -1) {
                Toast.makeText(mc, "听写已结束，请检查！", Toast.LENGTH_SHORT).show();
            } else if (Integer.parseInt(utteranceId) > 0) {
                if (tts != null) {
                    playSeekBar(false);
                    Toast.makeText(mc, "下一个！", Toast.LENGTH_SHORT).show();
                    tts.stop();
                    speakWordsFromIndex(words, currentWordIndex);  // 从下一个单词继续朗读
                }
            }
        }
    }



    // 处理保存按钮点击事件的方法
    private void handleSaveButtonClick() {
        // 权限检查
        if (pmsCheck()) {
            // 获取输入框中的文本内容
            String content = et.getText().toString().trim();
            // 如果文本内容为空，显示提示对话框
            if (content.isEmpty()) {
                showAlert("提示", "朗读内容不能为空！", "好的");
            } else {
                // 显示保存文件对话框
                showSaveFileDialog(content);
            }
        }
    }
    // 显示保存文件对话框的方法
    private void showSaveFileDialog(final String content) {
        // 创建文件名输入框
        final EditText fileNameInput = createFileNameInput();
        // 创建保存文件对话框的构建器
        AlertDialog.Builder builder = createSaveFileDialogBuilder(fileNameInput, content);
        // 创建并显示保存文件对话框
        AlertDialog alertDialog = builder.create();
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();
    }
    // 创建文件名输入框的方法
    private EditText createFileNameInput() {
        EditText fileNameInput = new EditText(mc);
        fileNameInput.setHeight(150);
        fileNameInput.setPadding(30, 0, 30, 0);
        fileNameInput.setHint("文件名...");
        return fileNameInput;
    }
    // 创建保存文件对话框的构建器的方法
    private AlertDialog.Builder createSaveFileDialogBuilder(final EditText fileNameInput, final String content) {
        return new AlertDialog.Builder(mc)
                .setTitle("请输入文件名")
                .setView(fileNameInput)
                .setNegativeButton("保存", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 处理保存文件确认
                        handleSaveFileConfirmation(fileNameInput, content);
                    }
                });
    }
    // 处理保存文件确认的方法
    private void handleSaveFileConfirmation(EditText fileNameInput, String content) {
        // 获取文件名输入框中的文件名
        String fileName = fileNameInput.getText().toString().trim();
        // 如果文件名为空，显示提示对话框
        if (fileName.isEmpty()) {
            showAlert("提示", "文件名不能为空！", "好的");
        } else {
            // 保存文本转语音文件
            saveTextToSpeechFile(content, fileName);
        }
    }
    // 保存文本转语音文件的方法
    //还未实现想要的功能。。。
    private void saveTextToSpeechFile(String content, String fileName) {
        // 创建保存音频文件的目录
        File audioDir = new File(Environment.getExternalStorageDirectory(), "听写小助手");
        if (!audioDir.exists()) {
            audioDir.mkdirs();
        }

        // 获取需要循环合成的次数
        setLoopNum();

        // 分割文本内容为单词数组
        String[] words = content.split("[\\p{P}\\p{S}\\s]+");

        // 拼接文本内容并重复指定次数
        StringBuilder sb = new StringBuilder();
        for (String word : words) {
            for (int i = 0; i < loopNum; i++) {
                sb.append(word);
            }
        }
        String synthesizedText = sb.toString();

        // 设置语音合成参数
        HashMap<String, String> myHashRender = new HashMap<>();
        myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, synthesizedText);

        // 合成文本为语音并保存为MP3文件
        int result = tts.synthesizeToFile(synthesizedText, myHashRender, String.valueOf(new File(audioDir, fileName + "_" + getDate() + ".mp3")));

        // 处理保存结果
        if (result == TextToSpeech.SUCCESS) {
            showAlert("保存成功", "文件路径：sdcard/听写小助手/" + fileName, "OK");
        } else {
            showAlert("保存失败", "保存文件时出现异常！", "确定");
        }
    }
    /**
     * 格式化当前日期作为文件名后缀
     *
     * @return
     */
    public String getDate() {
        @SuppressLint("SimpleDateFormat") SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        return df.format(new Date());
    }


    //权限检查
    private boolean pmsCheck() {
        int writeCheck = ContextCompat.checkSelfPermission(DictationModeActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int internetCheck = ContextCompat.checkSelfPermission(DictationModeActivity.this, Manifest.permission.INTERNET);
        if (writeCheck < 0 || internetCheck < 0) {
            AlertDialog.Builder builder = new AlertDialog.Builder(DictationModeActivity.this)
                    .setTitle("权限申请")
                    .setMessage("即将申请手机储存读写权限，该权限仅用于保存并导出音频文件。")
                    .setPositiveButton("好的", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(DictationModeActivity.this, new String[]{Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.INTERNET}, 2);
                        }
                    })
                    .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            AlertDialog alertDialog = builder.create();
            alertDialog.setCanceledOnTouchOutside(false);
            alertDialog.show();

            return false;
        } else {
            return true;
        }
    }

    /**
     * 开启或关闭滑块
     * 参数：state
     * 参数值：true开启，false关闭
     *
     * @param state
     */
    public void onOffSeekBar(final boolean state) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                pitchBar.setClickable(state);
                pitchBar.setEnabled(state);
                pitchBar.setSelected(state);
                pitchBar.setFocusable(state);
                speechRateBar.setClickable(state);
                speechRateBar.setEnabled(state);
                speechRateBar.setSelected(state);
                speechRateBar.setFocusable(state);
                ttsListSp.setEnabled(state);
                loop_switch.setEnabled(state);
                et.setEnabled(state);
                //loop_num_et.setEnabled(state);
                if (state) {
                    speakBtn.setVisibility(View.VISIBLE);
                    openConfigBtn.setVisibility(View.VISIBLE);
                    openConfigLinear.setBackgroundResource(R.drawable.def_mode_btn_white);
                    cameraButton.setVisibility(View.VISIBLE);
                    camera_L.setBackgroundResource(R.drawable.def_mode_btn_white);
                    playControl.setVisibility(View.GONE);
                    stopBtn.setVisibility(View.GONE);
                    tb_hide.setVisibility(View.GONE);
                } else {
                    speakBtn.setVisibility(View.GONE);
                    openConfigBtn.setVisibility(View.GONE);
                    openConfigLinear.setBackgroundColor(0x00FFFFFF);
                    cameraButton.setVisibility(View.GONE);
                    camera_L.setBackgroundColor(0x00FFFFFF);
                    playControl.setVisibility(View.VISIBLE);
                    stopBtn.setVisibility(View.VISIBLE);
                    tb_hide.setVisibility(View.VISIBLE);
                }
            }
        });
    }
    //播放控制面板控制
    private void playSeekBar(boolean seek) {
        if (seek){
            //隐藏pauseButton
            pauseButton.setVisibility(View.GONE);
            //显示playButton
            playButton.setVisibility(View.VISIBLE);
        }else {
            //隐藏playButton
            playButton.setVisibility(View.GONE);
            //显示pauseButton
            pauseButton.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 设置TextView文字
     * 参数：view_id，text_value
     * 参数值：view_id控件成员变量名，text_value要设置的文本内容
     *
     * @param view_id
     * @param text_value
     */
    public void setTextViewWord(final TextView view_id, final String text_value) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                view_id.setText(text_value);
            }
        });
    }

    /**
     * 读取历史记录
     *
     * @param ways
     */
    public void historyText(String ways) {
        // 获取名为"history_text_dic"的SharedPreferences实例，使用私有模式
        SharedPreferences history_text_dic = getSharedPreferences("history_text_dic", Context.MODE_PRIVATE);
        // 获取SharedPreferences的编辑器
        SharedPreferences.Editor editor = history_text_dic.edit();

        // 根据参数ways的值执行不同的操作
        if (ways.equals("read")) {
            // 如果ways为"read"，从SharedPreferences中获取名为"history_text_dic"的字符串数据
            String text = history_text_dic.getString("history_text_dic", "");
            // 将获取的字符串数据设置到EditText控件中
            et.setText(text);
        } else if (ways.equals("write")) {
            // 如果ways为"write"，将EditText中的文本内容存储到名为"history_text_dic"的SharedPreferences中
            editor.putString("history_text_dic", et.getText().toString());
            // 提交编辑器的修改
            editor.apply();
        }

        // 调用showWordNumber方法显示词语个数
        showWordNumber();
    }
    // 显示词语个数的方法
    private void showWordNumber() {
        // 从输入框中获取文本
        String str = et.getText().toString().trim();
        // 如果文本为空，则词语个数为0
        if (str.equals("")){
            terms = 0;
        }else {
            // 使用正则表达式分割字符串，以空格和标点符号作为分隔符
            String[] words = str.split("[\\p{P}\\p{S}\\s]+");
            // 获取词语个数
            terms = words.length;
        }
        // 设置显示词语个数的文本视图
        setTextViewWord(textNum, terms + "个词");

        // 从SharedPreferences中获取词典模式的起始字符串和结束字符串
        SharedPreferences config_dic_mode = getSharedPreferences("config_dic_mode", Context.MODE_PRIVATE);
        dic_start_str = config_dic_mode.getString("start_str","");
        dic_end_str = config_dic_mode.getString("end_str","");
    }
    //获取循环次数
    public void setLoopNum() {
        if (isLoop){
            if (loop_num_et.getText().toString().trim().equals("")) {
                loopNum = 3;
                loop_num_et.setText("3");
            } else if (Integer.parseInt(loop_num_et.getText().toString()) == 0) {
                loopNum = 3;
                loop_num_et.setText("3");
            } else {
                loopNum = Integer.parseInt(loop_num_et.getText().toString());
            }
        }else {
            loopNum = 3;
        }

    }

    // 获取TTS引擎列表数据
    public void getTtsListData() {
        // 获取原始列表
        List<TextToSpeech.EngineInfo> ttsEngines = AudioUtil.getTtsList(mc);
        if (ttsEngines != null) {
            // 设置TTS引擎选择下拉框
            setupTtsListSpinner(ttsEngines);
        }

        // 关闭TTS引擎
        shutdownTtsIfNotNull();

        // 初始化TTS引擎并设置监听器
        initializeTtsAndSetListeners();
    }
    // 设置TTS引擎选择下拉框
    private void setupTtsListSpinner(List<TextToSpeech.EngineInfo> ttsEngines) {
        final String[] ttsEngineNames = new String[ttsEngines.size()];
        for (int i = 0; i < ttsEngines.size(); i++) {
            TextToSpeech.EngineInfo engineInfo = ttsEngines.get(i);
            ttsEngineNames[i] = engineInfo.label;
            tts_map.put(engineInfo.label, engineInfo.name);
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, ttsEngineNames);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        ttsListSp.setAdapter(adapter);
    }
    // 关闭TTS引擎
    private void shutdownTtsIfNotNull() {
        if (tts != null) {
            tts.shutdown();
        }
    }
    // 初始化TTS引擎并设置监听器
    private void initializeTtsAndSetListeners() {
        // 获取选择的TTS引擎名称
        String selectedEngineName = tts_map.get(ttsListSp.getSelectedItem().toString());
        // 初始化TTS引擎
        tts = AudioUtil.initTTS(mc, selectedEngineName);

        // 设置TTS引擎的朗读进度监听器
        tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
            @Override
            public void onStart(String utteranceId) {
                // 处理朗读开始事件
                handleTtsStart(utteranceId);
            }

            @Override
            public void onDone(String utteranceId) {
                // 处理朗读完成事件
                handleTtsDone(utteranceId);
            }

            @Override
            public void onError(String utteranceId) {
                // 处理错误事件
            }

            @Override
            public void onError(String utteranceId, int errorCode) {
                // 处理错误事件
            }
        });
    }

    // 处理朗读开始事件
    private void handleTtsStart(String utteranceId) {
        // 设置当前朗读词语索引
        currentWordIndex = utteranceId;
        // 显示在读词语个数
        if (Integer.parseInt(utteranceId) > 0) {
            setTextViewWord(textNum, utteranceId + "/" + terms + "个词");
        }
    }
    // 处理朗读完成事件
    private void handleTtsDone(final String utteranceId) {
        // 停止朗读并等待1秒后退出
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            if (!tts.isSpeaking() && Integer.parseInt(utteranceId) == -1) {
                // 执行朗读完成后的操作
                handleTtsDoneActions();
            }
        }, 1000);
    }
    // 处理朗读完成后的操作
    private void handleTtsDoneActions() {
        currentWordIndex = "0";
        tts.stop();
        playSeekBar(false);
        onOffSeekBar(true);
        setTextViewWord(tb, "听写模式");
        setTextViewWord(textNum, terms + "个词");
        showAlert("提示", "听写结束！", "好的");
    }




    //显示提示框的方法
    private void showAlert(String title, String message, String buttonText) {
        sysToolUtil.msgAlert(title, message, buttonText, mc);
    }
    //提示朗读内容不能为空
    private void showEmptyContentAlert() {
        showAlert("提示", "朗读内容不能为空！", "好的");
    }

    @Override
    protected void onDestroy() {
        //
        AudioUtil.releaseTTS();

        // 释放内存资源
        OCR.getInstance(getApplicationContext()).release();
        if (alertDialog != null){
            alertDialog = null;
        }
        super.onDestroy();
    }

}
